import React, { Component } from 'react'
import { connect } from 'react-redux'
import { actionCreators } from './store'
import Wrapper from 'base/Wrapper'
import PageTable from 'base/PageTable'
import ActionModal from 'base/ActionModal'
import Loading from 'base/Loading'
import Search from './base/search'
import Forms from './base/forms'
import {
  AccountWrapper,
  ActionWrapper,
  ActionForm
} from './style'
import { ERR_OK } from 'api/config'
import { getList, actionList } from 'api/account'
import { accountListThead } from 'common/js/table'
import { filterLikeSearch } from 'common/js/util'
import { successNotify, errorNotify } from 'common/js/dom'

class Account extends Component {
  constructor (props) {
    super(props)

    this.tableProps = {
      rowKey: (row) => row['id'],
      columns: accountListThead(this)
    }

    this.editClick = this.editClick.bind(this)
    this.addClick = this.addClick.bind(this)
    this.actionCommit = this.actionCommit.bind(this)
    this.actionList = this.actionList.bind(this)
    this.actionCancel = this.actionCancel.bind(this)
    this.searchClick = this.searchClick.bind(this)
    this.searchFilter = this.searchFilter.bind(this)
  }

  render () {
    const { actionKey, loading, controllLoading } = this.props
    this.actionTitle = actionKey === 'save' ? '新增' : actionKey === 'update' ? '编辑' : '删除'

    return (
      <Wrapper title="账户管理">
        <AccountWrapper>
          <Search addClick={this.addClick} searchClick={this.searchClick} />
          <div className="table">
            <PageTable
              ref={(table) => this.pageTable = table}
              tableProps={this.tableProps}
              searchValue={this.searchFilter}
              getList={this.getList}
              controllLoading={controllLoading}
            />
          </div>
          </AccountWrapper>
        <Loading show={loading} />
        <ActionModal
          width="620px"
          title={this.actionTitle}
          okCallback={this.actionCommit}
          cancelCallback={this.actionCancel}
          ref={(modal) => this.modal = modal}
        >
          <ActionWrapper>
            <ActionForm>
              <Forms ref={(forms) => forms ? this.forms = forms.getWrappedInstance() : null}></Forms>
            </ActionForm>
          </ActionWrapper>
        </ActionModal>
      </Wrapper>
    )
  }

  async deleteClick ({row, index}) {
    this.modal.controlLoading(true)
    await this.actionList('delete', { id: row.id })
    this.modal.controlLoading(false)
  }

  editClick ({row, index}) {
    this.props.changeActionKey('update')
    this.props.changeFormData(row)
    this.modal.showModal()
  }

  addClick () {
    this.props.changeActionKey('save')
    this.props.changeFormData()
    this.modal.showModal()
  }

  actionCommit () {
    this.forms.validateFields(async (err, values) => {
      if (!err) {
        this.modal.controlLoading(true)
        const sendData = {id: this.props.formData.id, ...values}
        await this.actionList(this.props.actionKey, sendData)
        this.modal.controlLoading(false)
      }
    })
  }

  actionList (key, data) {
    return new Promise(async (resolve, reject) => {
      const res = await actionList(key, data)
      resolve()

      if (res.code === ERR_OK) {
        if (key === 'save' || key === 'update') {
          this.modal.hideModal()
        }
        this.pageTable.actionData()
        successNotify({
          message: '操作',
          description: `${this.actionTitle}成功`
        })
      } else {
        errorNotify({
          message: '操作',
          description: `${this.actionTitle}失败`
        })
      }
    })
  }

  actionCancel () {
    this.props.changeFormData()
    this.forms.resetFields()
  }

  searchClick () {
    this.pageTable.searchData()
  }

  searchFilter () {
    const property = []
    const value = []
    const { searchValue } = this.props

    searchValue.map((item, key) => {  // eslint-disable-line
      if (item) {
        property.push(key)
        if (key === 'userName') {
          value.push(filterLikeSearch(item))
        } else {
          value.push(item)
        }
      }
    })

    return {
      searchProperty: property.join(','),
      searchValue: value.join(',')
    }
  }

  async getList ({ page, searchValue, callback, complete }) {
    const res = await getList(page, searchValue)
    if (res.code === ERR_OK) {
      callback(res)
    }
    complete(res)
  }
}

const mapState = (state) => ({
  searchValue: state.getIn(['account', 'searchValue']),
  actionKey: state.getIn(['account', 'actionKey']),
  loading: state.getIn(['account', 'loading']),
  formData: state.getIn(['account', 'formData'])
})

const mapActions = (dispatch) => ({
  changeActionKey: (key) => {
    dispatch(actionCreators.changeActionKeyAction(key))
  },

  changeFormData: (data) => {
    dispatch(actionCreators.changeFormDataAction(data))
  },

  controllLoading: (bol) => {
    dispatch(actionCreators.changeLoadingAction(bol))
  }
})

export default connect(mapState, mapActions)(Account)
